package server

import (
	"4-26zk/comment/models/mysql"
	"4-26zk/comment/proto/product"
	"errors"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"time"
)

func ProductCreate(req *product.ProductCreateReq) (*product.ProductCreateResp, error) {
	s := uuid.New().String()
	m := mysql.Product{
		Model:              gorm.Model{},
		CategoryId:         int(req.CategoryId),
		ProductName:        req.ProductName,
		ProductCode:        s,
		ProductSelling:     req.ProductSelling,
		ProductImage:       req.ProductImage,
		VideoUrl:           req.VideoUrl,
		ProductStockUnitId: int(req.ProductStockUnitId),
	}
	err := mysql.ProductCreate(&m)
	if err != nil {
		return nil, errors.New("商品添加失败")
	}
	return &product.ProductCreateResp{Greet: "商品添加成功"}, nil
}

func ProductOtherInfoCreate(req *product.ProductOtherInfoCreateReq) (*product.ProductOtherInfoCreateResp, error) {
	info := mysql.ProductOtherInfo{
		Model:               gorm.Model{},
		AfterSalesStatus:    int(req.AfterSalesStatus),
		WithoutReasonStatus: int(req.WithoutReasonStatus),
		ProductStatus:       int(req.ProductStatus),
		NoSaleStatus:        int(req.NoSaleStatus),
		NoSaleTime:          time.Now(),
	}
	err := mysql.ProductOtherInfoCreate(&info)
	if err != nil {
		return nil, errors.New("添加失败")
	}
	return &product.ProductOtherInfoCreateResp{Greet: "添加成功"}, nil
}
func ProductSpecificationsCreate(req *product.ProductSpecificationsCreateReq) (*product.ProductSpecificationsCreateResp, error) {
	info := mysql.ProductSpecifications{
		Model:             gorm.Model{},
		ProductId:         int(req.ProductId),
		ProductSpec:       req.ProductSpec,
		ProductPackage:    req.ProductPackage,
		ImageSpec:         req.ImageSpec,
		SpecCode:          req.SpecCode,
		RetailPrice:       float64(req.RetailPrice),
		CostPrice:         float64(req.CostPrice),
		StockWarningValue: int(req.StockWarningValue),
		Stock:             int(req.Stock),
		Weight:            float64(req.Weight),
		SaleVolume:        int(req.SaleVolume),
	}
	err := mysql.ProductSpecificationsCreate(&info)
	if err != nil {
		return nil, errors.New("添加失败")
	}
	return &product.ProductSpecificationsCreateResp{Greet: "添加成功"}, nil
}

func ProductList(req *product.ProductListReq) (*product.ProductListResp, error) {
	list, err := mysql.ProductList(int(req.Page), int(req.Size))
	if err != nil {
		return nil, errors.New("查询失败")
	}
	var lists []*product.List
	for _, p := range list {
		lists = append(lists, &product.List{
			Id:                 int64(p.ID),
			CategoryId:         int64(p.CategoryId),
			ProductName:        p.ProductName,
			ProductSelling:     p.ProductSelling,
			ProductImage:       p.ProductImage,
			VideoUrl:           p.VideoUrl,
			ProductStockUnitId: int64(p.ProductStockUnitId),
		})
	}
	return &product.ProductListResp{
		List: lists,
	}, nil
}
